import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import request from '../utils/request'
import { useUserStore } from './userStore'
import { useMenuStore } from './useMenuStore'

export const useArticleStore = defineStore('article', () => {
  const articles = ref([])
  const comments = ref([])
  const currentCategory = ref('all')
  const userStore = useUserStore()
  const menuStore = useMenuStore()

  // 获取所有文章
  const fetchArticles = async () => {
    try {
      const data = await request.get('/articles')
      console.log(data)
      articles.value = data
    } catch (error) {
      console.error('获取文章失败:', error)
      throw error
    }
  }

  // 设置当前分类
  const setCategory = (category) => {
    currentCategory.value = category
  }

  // 根据分类获取文章
  const getArticlesByCategory = computed(() => {
    // 如果用户未登录，只显示全部文章
    if (!userStore.isLogin && menuStore.activeItemId !== 'all') {
      return []
    }

    // 首先根据分类过滤文章
    let filteredArticles = articles.value
    if (currentCategory.value !== 'all') {
      filteredArticles = filteredArticles.filter(article => 
        article.category === currentCategory.value
      )
    }

    // 根据菜单项进一步筛选文章
    switch (menuStore.activeItemId) {
      case 'all':
        return filteredArticles
        
      case 'subscribe':
        // 显示订阅用户的文章
        return filteredArticles.filter(article => 
          userStorae.userSubscriptions.includes(article.user_id)
        )
        
      case 'following':
        // 显示用户喜欢的文章
        return filteredArticles.filter(article => 
          userStore.userLikes.includes(article.id)
        )
        
      case 'comments':
        // 显示用户评论过的文章
        return filteredArticles.filter(article => 
          userStore.userComments.includes(article.id)
        )
        
      case 'share':
        // 显示用户转发的文章
        return filteredArticles.filter(article => 
          userStore.userShares.includes(article.id)
        )
        
      default:
        return filteredArticles
    }
  })

  // 从本地获取单篇文章
  const getArticleById = computed(() => {
    return (id) => articles.value.find(article => article.id === id)
  })


  // 获取用户的所有文章
  const getArticlesByUserId = computed(() => {
    return (userId) => articles.value.filter(article => article.user_id === userId)
  })

  // 获取最新的n篇文章
  const getLatestArticles = computed(() => {
    return (n = 5) => [...articles.value]
      .sort((a, b) => new Date(b.create_time) - new Date(a.create_time))
      .slice(0, n)
  })

  // 获取热门文章（根据点赞和评论数）
  const getPopularArticles = computed(() => {
    return (n = 5) => [...articles.value]
      .sort((a, b) => (b.comment_count + b.like_count) - (a.comment_count + a.like_count))
      .slice(0, n)
  })

  // API 请求方法
  const createArticle = async (articleData) => {
    try {
      if (!articleData.user_id) {
        throw new Error('用户未登录或ID无效')
      }

      console.log('Store中的文章数据:', articleData)

      const data = await request.post('/articles', {
        user_id: articleData.user_id,
        category: articleData.category,
        title: articleData.title,
        summary: articleData.summary,
        content: articleData.content
      })
      return data
    } catch (error) {
      console.error('创建文章失败:', error.response?.data || error.message)
      throw error
    }
  }

  const updateArticle = async (id, articleData) => {
    try {
      const data = await request.put(`/articles/${id}`, {
        category: articleData.category,
        title: articleData.title,
        summary: articleData.summary,
        content: articleData.content
      })
      return data
    } catch (error) {
      console.error('更新文章失败:', error)
      throw error
    }
  }

  const deleteArticle = async (id) => {
    try {
      await request.delete(`/articles/${id}`)
    } catch (error) {
      console.error('删除文章失败:', error)
      throw error
    }
  }

  // 获取文章评论
  const fetchComments = async (articleId) => {
    try {
      const data = await request.get(`/articles/${articleId}/comments`)
      // console.log('原始数据:', data)
      // console.log(articles.value);
      comments.value = data
      // console.log('comments.value:', comments.value)
      
      return comments.value
    } catch (error) {
      console.error('获取评论失败:', error)
      throw error
    }
  }

  // 添加评论
  const addComment = async ({ article_id, content }) => {
    try {
      const response = await request.post(`/articles/${article_id}/comments`, {
        content,
        user_id: userStore.currentUser?.id
      })
      return response.data
    } catch (error) {
      console.error('添加评论失败:', error)
      throw error
    }
  }

  // 点赞文章
  const likeArticle = async (articleId) => {
    try {
      await request.post(`/articles/${articleId}/${userStore.currentUser?.id}/like`)
    } catch (error) {
      console.error('点赞失败:', error)
      throw error
    }
  }

  // 取消点赞
  const unlikeArticle = async (articleId) => {
    try {
      await request.delete(`/articles/${articleId}/${userStore.currentUser?.id}/like`)
    } catch (error) {
      console.error('取消点赞失败:', error)
      throw error
    }
  }

  // 转发文章
  const shareArticle = async (articleId) => {
    try {
      await request.post(`/articles/${articleId}/${userStore.currentUser?.id}/share`)
    } catch (error) {
      console.error('转发失败:', error)
      throw error
    }
  }

  const checkLikeStatus = async (articleId, userId) => {
    try {
      return await request.get(`/articles/${articleId}/${userStore.currentUser?.id}/like/check`)
    } catch (error) {
      console.error('检查点赞状态失败:', error)
      throw error
    }
  }

  return {
    articles,
    comments,
    currentCategory,
    fetchArticles,
    getArticleById,
    getArticlesByUserId,
    getArticlesByCategory,
    setCategory,
    getLatestArticles,
    getPopularArticles,
    createArticle,
    updateArticle,
    deleteArticle,
    fetchComments,
    addComment,
    likeArticle,
    unlikeArticle,
    shareArticle,
    checkLikeStatus
  }
}) 